from django.shortcuts import render,redirect
from django.views.generic import FormView
from users.forms import UserLoginForm,UserRegisterForm
from django.contrib.auth import authenticate,login,logout
from users.models import User
from django.urls import reverse_lazy

# Create your views here.
class UserLogin(FormView):
    template_name = 'login.html'
    form_class = UserLoginForm
    # success_url = reverse_lazy("index")

    def form_valid(self, form):
        data = form.cleaned_data
        user = authenticate(**data)
        if user is not None:
            login(self.request, user)
        url = self.request.META['HTTP_REFERER']
        return redirect("index")

    def form_invalid(self, form):
        return redirect("index")
    #
    # def get_success_url(self):
    #     url = self.request.META['HTTP_REFERER']
    #     return redirect(url)
    #     # return render(request,'login.html')


class Register(FormView):
    template_name = 'register.html'
    form_class = UserRegisterForm
    success_url = reverse_lazy("userlogin")

    def form_valid(self, form):
        data = form.cleaned_data   #clean_data  是读取表单返回的值，以字典的形式。
        User.objects.create_user(**data)
        return super().form_valid(form)

def userlogout(request):
    logout(request)
    return redirect("index")



def aboutus(request):
    return render(request,'about.html')

def careers(request):
    return render(request,'careers.html')

def contact(request):
    return render(request,'contact.html')

def profile(request):
    return render(request,'404.html')

def company_register(request):
    return render(request,'register.html')

def wishlist(request):
    return render(request,'wishlist.html')

def single(request):
    return render(request,'single.html')